﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class PurchaseOrders : Form
    {
        public PurchaseOrders()
        {
            InitializeComponent();
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            
            // 初始化DataGridView的复选框列
            InitializeCheckBoxColumn();
            tbxpurchase.Text = string.Empty;
            tbxpurchase.WaterText = "请输入采购单号";
            tbxpurchase.SkinTxt.Text = string.Empty;
            tbxpurchase.SkinTxt.WaterText = "请输入采购单号";
            GetData();
        }
        
        private ApiClient _apiClient;
        private List<PurchaseOutput> _currentData; // 存储当前数据
        private List<PurchaseOutput> _selectedItems; // 存储选中的项目

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 2;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;

        /// <summary>
        /// 初始化DataGridView的复选框列
        /// </summary>
        private void InitializeCheckBoxColumn()
        {
            // 添加复选框列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "选择";
            checkBoxColumn.Name = "SelectColumn";
            checkBoxColumn.Width = 50;
            checkBoxColumn.FalseValue = false;
            checkBoxColumn.TrueValue = true;
            
            // 将复选框列插入到第一列
            dgvpurchaseorders.Columns.Insert(0, checkBoxColumn);
            
            // 设置复选框列的样式
            dgvpurchaseorders.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            
            // 绑定确定和取消按钮事件
            btnsure.Click += Btnsure_Click;
            btnquxiao.Click += Btnquxiao_Click;
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void Btnsure_Click(object sender, EventArgs e)
        {
            _selectedItems = new List<PurchaseOutput>();
            
            // 遍历DataGridView，获取选中的行
            for (int i = 0; i < dgvpurchaseorders.Rows.Count; i++)
            {
                DataGridViewRow row = dgvpurchaseorders.Rows[i];
                if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
                {
                    // 获取对应的数据对象
                    if (i < _currentData.Count)
                    {
                        _selectedItems.Add(_currentData[i]);
                    }
                }
            }
            
            if (_selectedItems.Count > 0)
            {
                // 这里可以返回选中的数据或进行其他处理
                MessageBox.Show($"已选择 {_selectedItems.Count} 项", "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请至少选择一项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void Btnquxiao_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 获取选中的项目
        /// </summary>
        public List<PurchaseOutput> GetSelectedItems()
        {
            return _selectedItems ?? new List<PurchaseOutput>();
        }

        // 定义用于解析登录响应的模型类
        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }
        
        private void dgvpurchaseorders_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<PurchaseOutput>>>(
                    endpoint: "Material/GetPurchaseShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 保存当前数据
                _currentData = response.pageData ?? new List<PurchaseOutput>();
                
                // 将数据绑定到 DataGridView
                dgvpurchaseorders.DataSource = _currentData;
                
                // 重新添加复选框列（因为数据绑定会清除列）
                if (dgvpurchaseorders.Columns.Count > 0 && dgvpurchaseorders.Columns[0].Name != "SelectColumn")
                {
                    DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                    checkBoxColumn.HeaderText = "选择";
                    checkBoxColumn.Name = "SelectColumn";
                    checkBoxColumn.Width = 50;
                    checkBoxColumn.FalseValue = false;
                    checkBoxColumn.TrueValue = true;
                    
                    dgvpurchaseorders.Columns.Insert(0, checkBoxColumn);
                    dgvpurchaseorders.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                }
            }
        }
        
        /// <summary>
        /// 查询采购
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnchick_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(tbxpurchase.Text))
            {
                queryParams["purchase_Number"] = tbxpurchase.Text;
            }
            // 调用改造后的 GetData，传入查询条件
            GetData(queryParams);
        }
    }
}
